package com.lagou.boot;

import java.util.UUID;

import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.lagou.handler.UserServiceHandler;
import com.lagou.request.JSONSerializer;
import com.lagou.request.RpcDecoder;
import com.lagou.request.RpcNode;
import com.lagou.request.RpcRequest;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

@Component
public class SimpleApplicationRunner implements ApplicationRunner {

    @Value("${zookeeper.ip}")
    private String zookeeperIp;

    @Value("${zookeeper.port}")
    private int zookeeperPort;

    @Value("${spring.application.name}")
    private String applicationName;

    @Value("${rpc.provider.port}")
    private int rpcProviderPort;

    // 创建一个方法启动服务器
    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 1.创建两个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        // 2.创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        // 3.配置启动引导对象
        serverBootstrap.group(bossGroup, workGroup)
            // 设置通道为NIO
            .channel(NioServerSocketChannel.class)
            // 创建监听channel
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                    // 获取管道对象
                    ChannelPipeline pipeline = nioSocketChannel.pipeline();
                    // 给管道对象pipeLine 设置编码
                    pipeline.addLast(new StringEncoder());
                    pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                    // 把我们自顶一个ChannelHander添加到通道中
                    pipeline.addLast(new UserServiceHandler());
                }
            });

        // 4.绑定端口
        serverBootstrap.bind(rpcProviderPort).sync();

        ZkClient zkClient = new ZkClient(zookeeperIp + ":" + zookeeperPort);
        UUID uuid = UUID.randomUUID();
        zkClient.createPersistent("/" + applicationName, true);
        RpcNode rpcNode = new RpcNode();
        rpcNode.setIp("127.0.0.1");
        rpcNode.setPort(rpcProviderPort);
        zkClient.createEphemeral("/" + applicationName + "/" + uuid, JSON.toJSONString(rpcNode));
    }
}
